package com.dis.user.controller.admin;

import com.dis.common.annotation.CheckPermission;
import com.dis.common.result.Result;
import com.dis.pojo.entity.Permission;
import com.dis.pojo.entity.Role;
import com.dis.user.service.PermissionService;
import com.dis.user.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/role")
@Api(tags = "角色管理接口")
@Slf4j
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @GetMapping("/list")
    @ApiOperation("获取角色列表")
    @CheckPermission("role:query")
    public Result<List<Role>> getRoleList() {
        List<Role> roles = roleService.getAllRoles();
        return Result.success(roles);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID获取角色")
    @CheckPermission("role:query")
    public Result<Role> getRoleById(@PathVariable Long id) {
        Role role = roleService.getRoleById(id);
        return Result.success(role);
    }

    @PostMapping
    @ApiOperation("新增角色")
    @CheckPermission("role:add")
    public Result<Boolean> addRole(@RequestBody Role role) {
        boolean success = roleService.addRole(role);
        return Result.success(success);
    }

    @PutMapping
    @ApiOperation("更新角色")
    @CheckPermission("role:edit")
    public Result<Boolean> updateRole(@RequestBody Role role) {
        boolean success = roleService.updateRole(role);
        return Result.success(success);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除角色")
    @CheckPermission("role:delete")
    public Result<Boolean> deleteRole(@PathVariable Long id) {
        boolean success = roleService.deleteRole(id);
        return Result.success(success);
    }

    @GetMapping("/{roleId}/permissions")
    @ApiOperation("获取角色拥有的权限列表")
    @CheckPermission("role:query")
    public Result<List<Permission>> getRolePermissions(@PathVariable Long roleId) {
        List<Permission> permissions = permissionService.getPermissionsByRoleId(roleId);
        return Result.success(permissions);
    }

    @PostMapping("/{roleId}/permissions")
    @ApiOperation("为角色分配权限")
    @CheckPermission("permission:assign")
    public Result<Boolean> assignPermissions(
            @PathVariable Long roleId,
            @RequestBody List<Long> permissionIds) {
        boolean success = roleService.assignPermissions(roleId, permissionIds);
        return Result.success(success);
    }
}
